package com.campus.filter;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.campus.domain.dto.UserDTO;
import com.campus.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.util.Collections;
import java.util.List;


@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        if(token == null){//token不存在，返回错误信息
            //放行
            filterChain.doFilter(request,response);//SecurityConfig类中的.antMatchers("/user/login").anonymous()配置，发现是登录操作，则让其继续执行后续的操作
            return;
        }
        //解析token
        Claims claims = null;
        try {
            claims = JwtUtil.parseJwt(token);
        } catch (Exception e) {
            throw new RuntimeException("token解析失败");
        }
        Long userId = claims.get("userId", Long.class);
        String userName = claims.get("userName", String.class);
        String avatar = claims.get("avatar", String.class);
        String jsonStr = claims.get("permissions", String.class);
        List<String> permissions = JSON.parseArray(jsonStr, String.class);
        UserDTO userDTO = new UserDTO(userId,userName,null,avatar, permissions);
        //把用户信息存入SecurityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDTO,null, Collections.emptyList());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request,response);
    }
}
